﻿using Furion.EventBus;
using Furion.JsonSerialization;
using Microsoft.Extensions.Logging;
using StackExchange.Profiling.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.Application
{
    /// <summary>
    /// 队列
    /// </summary>
    [AllowAnonymous, ApiDescriptionSettings("Business", Name = "TestEventBus", Order = 2, Tag = "队列")]
    public class TestEventBus : IDynamicApiController
    {
        private readonly IEventPublisher _eventPublisher;
        private readonly IEventBusFactory _eventBusFactory;
        public TestEventBus(IEventPublisher eventPublisher, IEventBusFactory eventBusFactory)
        {
            _eventPublisher = eventPublisher;
            _eventBusFactory = eventBusFactory;
        }

        /// <summary>
        /// 发布 ToDo:Create 消息
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous, HttpGet("/TestEventBus/Create"), ApiDescriptionSettings(Name = "Create")]
        public async Task CreateDoTo()
        {
            var modle = new Policy
            {
                Id= Yitter.IdGenerator.YitIdHelper.NextId(),
                CreatedTime = DateTime.Now,
                Contents = "<p>为优化调整能源结构、提高可再生能源利用比例，日前，宝龙街道在龙岗智慧家园举办屋顶分布式光伏开发试点工作宣讲会，以实实在在的政策支持分布式光伏发电项目，推进辖区光伏产业高质量发展。</p><p>宣讲会上，龙岗区发展和改革局及中国科学院专家深入解读《深圳市关于大力推进分布式光伏发电的若干措施》等文件，龙岗区供电局进一步介绍全区光伏项目建设情况。随后，宝龙街道优秀光伏企业创益集团对光伏工程基础知识、光伏项目建设流程及发展前景、光伏项目合作模式等方面进行介绍，并分享相关成功案例。参会各园区及企业负责人就安装屋顶分布式光伏的优点、收益、落地实施、节能降碳等问题与专家们展开热烈讨论。</p>",
                CreatedUserId = 0,
                CreatedUserName = "admin",
                IsDeleted = false,
                PostDepart = "龙岗政府在线",
                Statu = 1,
                Summay = "为优化调整能源结构、提高可再生能源利用比例，日前，宝龙街道在龙岗智慧家园举办屋顶分布式光伏开发试点工作宣讲会，以实实在在的政策支持分布式光伏发电项目，推进辖区光伏产业高质量发展。",
                Title = "宝龙街道举办屋顶分布式光伏开发试点工作宣讲会",
                UpdatedTime = DateTime.Now,
                UpdatedUserId = 0,
                UpdatedUserName = "admin"
            }; 

            await _eventPublisher.PublishAsync("ToDo:Create", modle.ToJson());
        }


        /// <summary>
        /// 高频发布 ToDo:Create 消息
        /// </summary>
        [AllowAnonymous, HttpGet("/TestEventBus/HighFrequency"), ApiDescriptionSettings(Name = "HighFrequency")]
        public void HighFrequencyEvents()
        {
            var modle = new Policy
            {
                CreatedTime = DateTime.Now,
                Contents = "<p>为优化调整能源结构、提高可再生能源利用比例，日前，宝龙街道在龙岗智慧家园举办屋顶分布式光伏开发试点工作宣讲会，以实实在在的政策支持分布式光伏发电项目，推进辖区光伏产业高质量发展。</p><p>宣讲会上，龙岗区发展和改革局及中国科学院专家深入解读《深圳市关于大力推进分布式光伏发电的若干措施》等文件，龙岗区供电局进一步介绍全区光伏项目建设情况。随后，宝龙街道优秀光伏企业创益集团对光伏工程基础知识、光伏项目建设流程及发展前景、光伏项目合作模式等方面进行介绍，并分享相关成功案例。参会各园区及企业负责人就安装屋顶分布式光伏的优点、收益、落地实施、节能降碳等问题与专家们展开热烈讨论。</p>",
                CreatedUserId = 0,
                CreatedUserName = "admin",
                IsDeleted = false,
                PostDepart = "龙岗政府在线",
                Statu = 1,
                Summay = "为优化调整能源结构、提高可再生能源利用比例，日前，宝龙街道在龙岗智慧家园举办屋顶分布式光伏开发试点工作宣讲会，以实实在在的政策支持分布式光伏发电项目，推进辖区光伏产业高质量发展。",
                Title = "宝龙街道举办屋顶分布式光伏开发试点工作宣讲会",
                UpdatedTime = DateTime.Now,
                UpdatedUserId = 0,
                UpdatedUserName = "admin"
            };



            Parallel.For(0, 100, (i) =>
            {
                modle.Title = "宝龙街道举办屋顶分布式光伏开发试点工作宣讲会" + i;
                
                //_eventPublisher.PublishAsync("ToDo:Create", modle.ToJson());

                _eventPublisher.PublishDelayAsync("ToDo:Create", 500, modle.ToJson());
            });
        }


    }


    public class ToDoEventSubscriber : IEventSubscriber, ISingleton
    {
        private readonly ILogger<ToDoEventSubscriber> _logger;
        private readonly IJsonSerializerProvider _jsonSerializer;

        public ToDoEventSubscriber(ILogger<ToDoEventSubscriber> logger
            , IJsonSerializerProvider jsonSerializer)
        {
            _logger = logger;
            _jsonSerializer = jsonSerializer;
        }

        [EventSubscribe("ToDo:Create")]
        public async Task CreateToDo(EventHandlerExecutingContext context)
        {
            var todo = context.Source;

            var node = _jsonSerializer.Deserialize<Policy>(todo.Payload.ToString());
            node.Id = Yitter.IdGenerator.YitIdHelper.NextId();
            string s = "";
            s += " \r\n " + node.Title;
            s += " \r\n " + node.Summay;
            s += " \r\n " + node.CreatedUserName;
            s += " \r\n " + node.Contents;

            _logger.LogInformation("接收ToDo：", s);          

            var rs = await App.GetService<IRepository<Policy>>().InsertNowAsync(node);

             
            s += " \r\n 主键:" + rs;

            //_logger.LogInformation("创建一个 ToDo：{Name}", todo.Payload);

            _logger.LogInformation("主键：", s);

            await Task.CompletedTask;
        }

    }
}
